package com.gonsin.gmessage.logic.client;

import com.gonsin.gmessage.annotations.GMessageEnvironment;
import com.gonsin.gmessage.logic.model.GMessageModel;
import com.gonsin.gmessage.logic.mqtt.MqttClientManager;
import com.gonsin.gmessage.logic.mqtt.OnlineDeviceBo;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Qualifier("gmessageClientService")
@Slf4j
public class ClientServiceImpl implements IClientService{


//    @Autowired private MqttGateWay mqttGateWay;
    @Autowired private MqttClientManager mqttGateWay;

    // connectionId => OnlineDeviceBo 在线的设备
    private Map<String, OnlineDeviceBo> mqttConnectionMap = new ConcurrentHashMap<>();

    //    /**
//     * ip map
//     */
//    private Map<String, String> ipMap = new ConcurrentHashMap<>();
    private Map<String, OnlineDeviceBo> onlineMap = new ConcurrentHashMap<>();



    @Override
    public boolean isOnline(String mac) {
        if(mac == null){
            return false;
        }
        return onlineMap.containsKey(mac);
    }

    @Override
    public Map<String, OnlineDeviceBo> getAllOnline() {
        return new HashMap<>(onlineMap);
    }

    @Override
    public void notifyClientOnline(String connectionId, OnlineDeviceBo client) {
        mqttConnectionMap.put(connectionId, client);
        onlineMap.put(client.getMac(), client);
        log.debug("mac = " + client.getMac() + "，上线");
        GMessageModel message = GMessageModel.create("client", "online")
                .args("online", "online")
                .args("mac", client.getMac())
                .args("connectionId", connectionId);
        String payload = new Gson().toJson(message);
        mqttGateWay.publish("venus/client/online", 2, payload);
    }

    @Override
    public void notifyClientOffline(String connectionId) {
        OnlineDeviceBo bo = mqttConnectionMap.remove(connectionId);
        if(bo == null){
            return;
        }
        onlineMap.remove(bo.getMac());
        mqttConnectionMap.remove(bo.getConnectionId());
        if(GMessageEnvironment.LOG){
            log.debug("mac = " + bo.getMac() + "，下线");
        }
        GMessageModel message = GMessageModel.create("client", "online")
                .args("online", "offline")
                .args("mac", bo.getMac())
                .args("connectionId", connectionId);
        String payload = new Gson().toJson(message);
        mqttGateWay.publish("venus/client/online", 2, payload);
    }
}
